// 自定义底部导航栏

import {
  deepClone,
  isEmpty,
  jsonToQuery
} from "../../js/newUtil"
import {
  api
} from "../../js/util"
import {
  router
} from '../../js/router'
const componentBehavior = require('../../js/common/ComponentBehavior')
import { setStorageSync } from "../../js/compatible"
import { getRouterParams } from "../../js/modules/theme"

const app = getApp()

Component({
  /**
   * 组件的属性列表
   */
  properties: {

  },

  /**
   * 组件的初始数据
   */
  data: {
    tabbar: [], // 导航栏列表
    activeIndex: 0, // 当前活动的导航栏
    cartIndex: -1, // 购物车所在位置，用于设置显示数量等功能
    mainColor: api.titleColor || "#e56b14", //主题色
    isIphoneX: app.globalData.isIphoneX, //苹果底部白线
  },

  lifetimes: {
    attached() {
      this.getTabbar()
    }
  },
  pageLifetimes: {
    show() {
      this.setActiveIndex()
    }
  },

  behaviors: [componentBehavior],
  /**
   * 组件的方法列表
   */
  methods: {
    /**
     * 获取tabbar列表
     */
    getTabbar: async function () {
      let tabbar = await this.getGlobalTabbar()
      if (isEmpty(tabbar)) {
        tabbar = {
          list: [],
          originList: []
        }
      }
      let list = tabbar.list || []
      // 购物车所在位置index
      let index = list.findIndex(item => {
        let url = item.pagePath || ''
        return item.key == 'cart' || url.includes('cart')
      })
      this.setData({
        tabbar: tabbar,
        cartIndex: index
      })
      this.setActiveIndex()
    },
    /**
     * 获取存放在app中的tabbar信息
     */
    getGlobalTabbar() {
      return new Promise((resolve) => {
        if (!isEmpty(app.globalData.tabBar)) {
          if (!isEmpty(app.globalData.tabBar.list)) {
            resolve(app.globalData.tabBar)
            return
          }
        }
        let time = 0
        const STEP = 100
        const TIMEOUT = 30000
        let interval = setInterval(() => {
          if (time > TIMEOUT) {
            clearInterval(interval)
            resolve(null)
            return
          }
          if (!isEmpty(app.globalData.tabBar)) {
            if (!isEmpty(app.globalData.tabBar.list)) {
              clearInterval(interval)
              resolve(app.globalData.tabBar)
              return
            }
          }
          time += STEP
        }, STEP)
      })
    },
    /**
     * 点击底部导航
     * @param {*} e 
     */
    tapTabbar(e) {
      let index = e.currentTarget.dataset.index
      let {
        tabbar
      } = this.data
      let list = tabbar.list || []
      let item = list[index] || {}
      let url = item.pagePath || ''
      let type = item.type
      let param = item.url
      let fastId = item.fastId
      let cid = item.cid
      app.dns.cid = cid || 0
      // 当导航为H5链接时，修改部分页面跳转，改为跳转为小程序内页面而不是H5
      let bool = this.linkTo(url)
      if (bool) {
        return
      }
      // 设置跳转前的页面数据，如商品分类id，搜索关键词等
      let otherParams = this.setBeforeRouteData(index)
      let hasNav = otherParams.hasNav // 是否显示商品列表左侧目录
      // 跳转快速下单页面，顶部tab切换
      if (fastId) {
        setStorageSync('tabcurrent', fastId)
      }
      if (type == 2) {
        if (hasNav) {
          url = `${url}?hasnav=${true}`
        }
        wx.navigateTo({
          url,
          fail() {
            wx.switchTab({
              url
            })
          }
        })
        return
      }
      if (type == 1) {
        if (hasNav) {
          url = `${url}?hasnav=${true}`
        }
        setStorageSync('tabindex', index)
        wx.switchTab({
          url,
          fail() {
            wx.navigateTo({
              url
            })
          }
        })
        return
      }
      if (type == 3) {
        if (hasNav) {
          url = `${url}?hasnav=${true}&${param}`
        } else {
          url = `${url}?${param}`
        }
        wx.navigateTo({
          url,
          fail() {
            wx.switchTab({
              url
            })
          }
        })
        return
      }
      if (type == 4 && url == 'scan') {
        wx.scanCode({
          success: (res) => {
            app.globalData.product_list.index_search_keyword = res.result
            router.navigate({
              path: "productList",
              params: {
                keywords: res.result
              }
            })
          }
        })
        return
      }
    },
    /**
     * 通过链接和入参判断当前页面是否为底部导航页面
     */
    setActiveIndex() {
      let pages = getCurrentPages()
      let thisPage = pages[pages.length - 1]
      let route = thisPage.route
      let options = thisPage.options
      let reg1 = /^\//
      let reg2 = /\?/
      let activeIndex = -1
      let {
        tabbar
      } = this.data
      let list = tabbar.list || []
      options = jsonToQuery(options)
      // 路由最前面如果为 / 则去除它
      if (reg1.test(route)) {
        route = route.slice(1)
      }
      for (let i in list) {
        let url = list[i].pagePath || ''
        if (reg1.test(url)) {
          url = url.slice(1)
        }
        // 存在参数则需要同时满足路由和参数一致
        // 如：/pages/product/index?id=10 与 /pages/product/index?id=20 
        // 这两个页面同时配置到底部导航栏时，不判断参数会导致底部导航都将前一个设为高亮
        if (reg2.test(url)) {
          let query = url.slice(url.indexOf('?') + 1)
          url = url.slice(0, url.indexOf('?'))
          if (url == route && options == query) {
            activeIndex = i
            break
          }
        } else {
          // 路由相同
          if (route == url) {
            activeIndex = i
            break
          }
        }
      }
      this.setData({
        activeIndex
      })
    },
    /**
     * 设置底部导航badge红色内容区域
     * @param {Number|String} index 
     * @param {String} text 
     */
    setTabBarBadge(index, text) {
      let {
        tabbar
      } = this.data
      // 只有一个参数时，默认为设置购物车数量
      if (!isEmpty(index) && isEmpty(text)) {
        text = index
        index = this.data.cartIndex
      }
      // 底部导航只有5个
      if (index < 0 || index > 4) {
        return
      }
      try {
        tabbar.list[index].badge = text
        this.setData({
          tabbar
        })
      } catch (error) {
        console.log('设置底部badge失败', error)
      }
    },
    /**
     * 移除底部导航badge红色内容区域
     * @param {Number|String} index 
     */
    removeTabBarBadge(index) {
      let {
        tabbar
      } = this.data
      try {
        tabbar.list[index].badge = ''
        this.setData({
          tabbar
        })
      } catch (error) {
        console.log('清空badge失败', error)
      }
    },
    /**
     * 设置跳转页面前的数据
     * @param {*} index 点击项的下标
     * 
     * 商品标签等要特殊处理，提前设置全局变量数据
     * 
     * 参考 /js/modules/theme.js 中的 getFootBar 方法
     */
    setBeforeRouteData(index = -1) {
      if (index == -1) {
        return {
          hasNav: false
        }
      }
      let {
        tabbar
      } = this.data
      let originList = tabbar.originList || []
      let item = originList[index] || {}
      let links = ''
      if (item.Link) {
        links = (item.Link).toLowerCase()
      } else if (item.Keyword) {
        links = (item.Keyword).toLowerCase()
      }
      let ps = links.split('?')
      let param = ''
      if (ps.length > 1) {
        param = ps[1]
      }
      // 商品分类、商品列表等页面需要分类id，tagid等参数
      if (links == 'category' || links.indexOf('quick.aspx') > -1 || links.indexOf('product/list.aspx') > -1) {
        //品牌id
        let bid = getQueryString("bid", param);
        if (bid != null) {
          app.globalData.product_list.bid = bid;
        } else {
          app.globalData.product_list.bid = 0; //清理品牌数据
        }
        //分类id
        let cid = getQueryString("cid", param);
        if (cid != null) {
          app.globalData.product_list.cid = cid;
        } else {
          app.globalData.product_list.cid = 0
        }
        //关键词
        let index_search_keyword = getQueryString("sm", param);
        if (index_search_keyword != null) {
          app.globalData.product_list.index_search_keyword = index_search_keyword;
        } else {
          app.globalData.product_list.index_search_keyword = ''
        }
        //促销规则id
        let rule_id = getQueryString("promid", param);
        if (rule_id != null) {
          app.globalData.product_list.rule_id = rule_id;
        } else {
          app.globalData.product_list.rule_id = -1
        }
        //标签id
        let tag_id = getQueryString("tagid", param);
        if (tag_id != null) {
          app.globalData.product_list.tag_id = tag_id;
        } else {
          app.globalData.product_list.tag_id = 0
        }
        // 默认商品列表和固定链接中的商品，需要显示侧边目录栏，固定链接中的商品列表不显示侧边栏
        if (links == 'category' || links.indexOf('quick.aspx') > -1) {
          return {
            hasNav: true
          }
        }
      }
      return {
        hasNav: false
      }
    },
    /**
     * 当为部分页面时修改跳转链接
     * 如将H5的页面改为小程序内页面
     * 同theme中的linkTo方法类似
     * @param {*} link 链接
     * @returns 是否已更改并跳转
     */
    linkTo(link) {
      let url = deepClone(link)
      if (url == null || url == undefined || url == "") {
        return false
      }
      if (url.indexOf('pages/common/medium/index?url=') > -1) {
        let arr = url.split('?url=')
        if (arr.length > 1) {
          url = arr[1]
          url = decodeURIComponent(url)
        }
      }
      if (url.indexOf('wxa.redirect?') > -1) {
        url = url
      } else {
        url = url.toLowerCase()
      }
      let ps = url.split('?')
      let path = ''
      let param = ''
      if (ps.length > 1) {
        param = ps[1]
      }
      if (url.indexOf('couponsdetails') > -1 || url.indexOf('store/coupon/detail') > -1) {
        path = "couponDetail"
        router.navigate({
          path: path,
          params: getRouterParams(param)
        })
      }
      return false
    },
  }
})

function getQueryString(name, param) {
  let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
  let r = param.match(reg);
  if (r != null) return unescape(r[2]);
  return null;
}